import { CourseWatchEntity } from "@/typings/course";
import { LiveRoom } from "@/typings/live";
import { defineStore } from "pinia";
import { checkEntrance, getRoomData, getRoomWatchData } from "../LiveNewApi";
import { RoomType } from "@/enums/request-enum";
import { useLocationParams } from "@/store/useLocationStore";
import dayjs from "dayjs";
import { usePlayerStore } from "@/store/usePlayer";
import { http } from "@/utils/http";

const useLiveDataStore = defineStore("live", {
  state: () => ({
    roomData: null as LiveRoom | null,
    roomWatchData: null as CourseWatchEntity | null,
    shareUserId: null as string | null,
    watchType: null as string | null
  }),
  getters: {
    roomParams() {
      const { getParam } = useLocationParams();
      const playerStore = usePlayerStore();
      return {
        roomId: this.roomData?.roomId,
        watchRecordId: this.roomWatchData?.watchRecordId,
        roomType: RoomType.LIVE,
        inviteCode: getParam("inviteCode"),
        shopId: getParam("shopId") || getParam("spId"),
        dealId: getParam("dealerId"),
        screeningId: this.roomData?.screeningId,
        subjectId: this.roomData?.subjectId || getParam("sId"),
        watchType: this.watchType,
        totalDuration: playerStore.realProgress,
      };
    },
  },
  actions: {
    async checkEntrance() {
      const data = await checkEntrance(this.roomParams);
      return data;
    },

    async recordAnswerAttempt() {
      try {
        const data = await http.request({
          url: "/live/record-answer",
          headers: { application: "json" },
          method: "POST",
          data: {
            ...this.roomParams
          }
        });
        this.roomWatchData.answerCount = data
      } catch (err: any) {
        console.error(err);
      }
    },

    async fetchRoomData(roomId: string) {
      const data = await getRoomData({ ...this.roomParams, roomId });
      if (data) {
        data.streamStartTime =
          data.streamStartTime && dayjs(data.streamStartTime).toISOString();
        data.streamEndTime =
          data.streamEndTime && dayjs(data.streamEndTime).toISOString();
        data.transcribe.openStartTime =
          data.transcribe.openStartTime &&
          dayjs(data.transcribe.openStartTime).toISOString();
        data.transcribe.openEndTime =
          data.transcribe.openEndTime &&
          dayjs(data.transcribe.openEndTime).toISOString();
        this.roomData = data;
      }
      return data;
    },
    async fetchRoomWatchData(watchType?: "REAL_TIME" | "PLAY_BACK") {
      const { getParam } = useLocationParams();
      if (watchType) {
        this.watchType = watchType
      }
      const data = await getRoomWatchData({
        ...this.roomParams,
        watchType: this.watchType || (this.isLiveEnd() ? "PLAY_BACK" : "REAL_TIME"),
        shareUserId: this.shareUserId,
      });
      if (data) {
        const { sign1st, sign2nd, sign3rd } = data;
        const { signInRedPacket, signInNum } = this.roomData?.sign || {};
        if (signInRedPacket === 1) {
          // 获取sign1st,sign2nd,sign3rd不为空的数量
          const signCount = [sign1st, sign2nd, sign3rd].filter(
            item => item !== null
          ).length;
          if (signCount >= signInNum) {
            data.isSigned = 1;
          } else {
            data.isSigned = 0;
          }
        }
        this.roomWatchData = data;
      }
      return data;
    },
    setShareUserId(userId) {
      this.shareUserId = userId
    },
    updateRoomWatchData(roomWatchData) {
      this.roomWatchData = roomWatchData
    },
    isLiveEnd() {
      const now = Date.now();
      if (
        this.roomData?.transcribe.openType !== 0 &&
        new Date(this.roomData?.transcribe.openStartTime).getTime() <= now
      ) {
        return true;
      }
      if (
        this.roomData?.streamEndTime &&
        new Date(this.roomData?.streamEndTime).getTime() <= now
      ) {
        return true;
      }
      return false;
    }
  },
});
export default useLiveDataStore;

export type LiveDataStore = ReturnType<typeof useLiveDataStore>;
